package com.xianxing.gateway.web.filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.filter.OrderedFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 访问过滤器 用户鉴权
 */
@Component
public class AccessFilter implements Ordered, GlobalFilter {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final String LOGIN_URL="http://127.0.0.1:80/api/oauth2/login";
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取request和response
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //判断请求是否为登录请求
        if(request.getURI().getPath().contains("/user/login")){
            //登录请求直接放行
            return chain.filter(exchange);
        }
        //从cookie获取jti
        String jti=this.getJtiFromCookie(request);
        if(StringUtils.isEmpty(jti)){
            //jti不存在跳转到登录页面
            return this.toLoginPage(LOGIN_URL+"?from="+request.getURI().getPath(),response);
        }
        //通过jti获取jwt
        String jwt =  stringRedisTemplate.boundValueOps(jti).get();
        if(StringUtils.isEmpty(jwt)){
            //jwt不存在跳转到登录页面
            return this.toLoginPage(LOGIN_URL+"?from="+request.getURI().getPath(),response);
        }
        //jwt存入请求头
        request.mutate().header("Authorization","Bearer "+jwt);
        return chain.filter(exchange);
    }

    /**
     * 跳转到登录界面
     * @param
     * @param response
     */
    private Mono<Void> toLoginPage(String loginUrl, ServerHttpResponse response) {
        //设置状态码
        response.setStatusCode(HttpStatus.SEE_OTHER);
        //设置跳转uri
        response.getHeaders().set("Location",loginUrl);
        //完成跳转
        return response.setComplete();
    }

    /**
     * 从cookie获取jti
     * @param request
     * @return
     */
    private String getJtiFromCookie(ServerHttpRequest request) {

        HttpCookie uid = request.getCookies().getFirst("jti");
        if(!StringUtils.isEmpty(uid)){
            return uid.getValue();
        }
        return null;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
